 //
//  XHSMeViewController.m
//  Lottery
//
//  Created by 李宗帅 on 16/7/9.
//  Copyright © 2016年 李宗帅. All rights reserved.
//

#import "YCLMeViewController.h"
#import "HDAccount.h"
#import "YCLLoginModelManager.h"
#import "YCLLoginViewController.h"
#import "LTXNavgationViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "UINavigationItem+YCLMargin.h"
#import "YCLHtmlViewController.h"
#import "YCLMeDescView.h"
#import "YCLMeModelManager.h"
#import "ReceiveGoodsVC.h"
#import "HDSellerObject.h"
#define FOLLOWNUMBER_TAG 2020

@interface YCLMeViewController ()<UITextViewDelegate,YCLMeDescViewDelegate>
{
    UIView *accountDetailsView;
    
}
@property (nonatomic, strong) UIView *headCenterView;

@property (nonatomic, strong) UIButton *loginBtn;//登录按钮

@property (nonatomic, strong) UIImageView *iconView;//头像

@property (nonatomic, strong) UILabel *moneyL; //余额

@property (nonatomic, strong) UILabel *cashL; //积分

@property (nonatomic, strong) UILabel *redEnvelopeCount;//红包个数

@property (nonatomic, strong) YCLMeModelManager *modelManager;


@end

@implementation YCLMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addHeadView];
    [self setupHeadView];
    
    [self accountDetails];
    [self setupContentView];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupNav];
    HDAccount *accout = [HDAccount account];
    //每次进来先判断是否登录了 登录了就请求当前页面数据  包括余额
    if (accout)
    {
        self.loginBtn.userInteractionEnabled = NO;
        [self.iconView setImage:[UIImage imageNamed:@"pic_head_120x120"]];
        [self.loginBtn setTitle:accout.username forState:UIControlStateNormal];
        //因为余额和冻结金额随时会发生变化  所以每次要请求一下
        [self setupDescData];
    }
    else{
        self.iconView.image =[UIImage imageNamed:@"pic_head_120x120"];
        self.loginBtn.userInteractionEnabled = YES;
        [self.loginBtn setTitle:@"登录 | 注册" forState:0];
        self.moneyL.text = @"0 USD";
        self.cashL.text = @"0 分";
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

//状态栏为白色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

//导航栏设置
- (void)setupNav {
    

}

- (void)createLeftView {
    
    UIBarButtonItem *leftButton = [UIBarButtonItem js_itemWithImage:@"icon_customerservice_44x44" highImage:@"icon_customerservice_44x44" target:self action:@selector(addUserClick)];

    UIBarButtonItem *leftSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:nil action:nil];
    leftSpacer.width = 15;//默认-5
    [self.navigationItem setupLeftBarButtonItems:@[leftSpacer, leftButton]];
    
}


- (void)createTitleView
{
    UILabel* label = [[UILabel alloc]init];
    label.textColor = JSRGBColor(0xff, 0xff, 0xff);
    label.text = @"我的";
    label.font = [UIFont boldSystemFontOfSize:18];
    CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName,nil]];
    label.frame = CGRectMake(0, 0, size.width, 18);
    
    self.navigationItem.titleView = label;
}



- (void)createRightView {
    UIBarButtonItem *rightButton = [UIBarButtonItem js_itemWithImage:@"icon_news_44x44" highImage:@"icon_news_44x44" target:self action:@selector(setting)];
    UIBarButtonItem *rightSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:nil action:nil];
    rightSpacer.width = 1;//默认-5
  //  [self.navigationItem setupRightBarButtonItems: @[rightSpacer, rightButton]];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}


/**
 生成头部View
 */
- (void)addHeadView {
    
    UIImageView* barView = [[UIImageView alloc]init];
    barView.image = [UIImage imageNamed:@"headBgView"];
    barView.frame = CGRectMake(0, SafeAreaTopHeight, CGRectGetWidth(self.view.bounds), barView.image.size.height);
    [self.view addSubview:barView];
}

- (void)setupHeadView
{
    UIView *headCenterView = [[UIView alloc]init];
    [self.view addSubview:headCenterView];
    _headCenterView = headCenterView;
    [headCenterView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.view).offset(75);
        make.left.equalTo(self.view).offset(4);
        make.right.equalTo(self.view).offset(-4);
        make.height.equalTo(@(200));
    }];
    UIImageView *headCenterImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_head"]];
    [headCenterView addSubview:headCenterImg];
    [headCenterImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.headCenterView);
    }];
    
    //头像
    self.iconView = [[UIImageView alloc]init];
    self.iconView.userInteractionEnabled = YES;

    self.iconView.image=[UIImage imageNamed:@"pic_head_120x120"];
    self.iconView.layer.cornerRadius = 60/2;
    self.iconView.clipsToBounds = YES;
    [headCenterView addSubview:self.iconView];
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headCenterView).offset(22.5);
        make.centerX.equalTo(headCenterView);
        make.height.width.equalTo(@(60));
    }];
    
    //头像按钮
    UIButton *iconBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    iconBtn.frame = self.iconView.frame;
    [headCenterView addSubview:iconBtn];
    [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.iconView);
    }];
    [iconBtn addTarget:self action:@selector(personMessage) forControlEvents:UIControlEventTouchUpInside];
    //登录按钮
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //判断是否登录
    HDAccount *accout = [HDAccount account];
    if (!accout) {
        [self.loginBtn setTitle:@"登录 | 注册" forState:0];
    }
    else
    {
        [self.loginBtn setTitle:@"" forState:0];
    }
    self.loginBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.loginBtn setTitleColor:LTXDefaultsLineColor forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(logIn:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginBtn sizeToFit];
    [headCenterView addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(iconBtn);
        make.top.equalTo(iconBtn.mas_bottom).offset(10);
    }];

}


//账户明细的view模块
- (UIView *)accountDetails
{
    CGFloat viewW = ScreenW - 8;
    //余额,提现金额
    accountDetailsView = [[UIView alloc]init];
    accountDetailsView.userInteractionEnabled = YES;
    accountDetailsView.frame = CGRectMake(4, 204.5, viewW, 60);
    accountDetailsView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:accountDetailsView];
    
    //余额
    self.moneyL = [[UILabel alloc]init];
    
    self.moneyL.font = [UIFont boldSystemFontOfSize:16];
    self.moneyL.textAlignment = NSTextAlignmentCenter;
    self.moneyL.text = @"0 元";
    [self.moneyL sizeToFit];
    self.moneyL.frame = CGRectMake(10, 0, viewW/2 - 20, self.moneyL.height);
    [accountDetailsView addSubview:self.moneyL];
    
    UIButton *moneyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    moneyBtn.frame = self.moneyL.frame;
    [accountDetailsView addSubview:moneyBtn];
    [moneyBtn addTarget:self action:@selector(clickMoneyBtn) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moneyDesc = [[UILabel alloc]init];
    moneyDesc.textColor = [UIColor grayColor];
    moneyDesc.font = [UIFont systemFontOfSize:12];
    moneyDesc.text = @"余额";
    moneyDesc.textAlignment = NSTextAlignmentCenter;
    [moneyDesc sizeToFit];
    moneyDesc.frame = CGRectMake(0, CGRectGetMaxY(self.moneyL.frame) + 10, self.moneyL.width, moneyDesc.height);
    [accountDetailsView addSubview:moneyDesc];
    
    //可提现金额
    self.cashL = [[UILabel alloc]init];
    self.cashL.font = [UIFont boldSystemFontOfSize:16];
    self.cashL.textAlignment = NSTextAlignmentCenter;
    self.cashL.text = @"0 元";
    [self.cashL sizeToFit];
    self.cashL.frame = CGRectMake(viewW/2 + 10, 0, viewW/2 - 20, self.cashL.height);
    [accountDetailsView addSubview:self.cashL];
    
    UILabel *cashDesc = [[UILabel alloc]init];
    cashDesc.text = @"积分";
    cashDesc.textColor = [UIColor grayColor];
    cashDesc.font = [UIFont systemFontOfSize:12];
    cashDesc.textAlignment = NSTextAlignmentCenter;
    [cashDesc sizeToFit];
    cashDesc.frame = CGRectMake(self.cashL.x, CGRectGetMaxY(self.cashL.frame) + 10, self.cashL.width, cashDesc.height);
    [accountDetailsView addSubview:cashDesc];
    
    UIButton *cashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cashBtn.frame = CGRectMake(self.cashL.x, 0, self.cashL.width, self.cashL.height);
    [accountDetailsView addSubview:cashBtn];
    [cashBtn addTarget:self action:@selector(clickCashBtn) forControlEvents:UIControlEventTouchUpInside];

    return accountDetailsView;
}


/**
 创建内容View
 */
- (void)setupContentView
{
    //这里放收货地址和退出登录  //后期可以无限添加
    UIScrollView *scrollview = [[UIScrollView alloc]init];
    scrollview.backgroundColor = [UIColor clearColor];
    scrollview.showsVerticalScrollIndicator = NO;
    scrollview.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:scrollview];
    
    [scrollview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.headCenterView.mas_bottom);
    }];
    //我的收益
    YCLMeDescView *myIncomeView = [[YCLMeDescView alloc]initWithModels:[self.modelManager obtainMyIncomeModels]];
    myIncomeView.delegate = self;
    [scrollview addSubview:myIncomeView];
    
    [myIncomeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(79));
        make.top.equalTo(scrollview.mas_top).offset(30);
    }];
    
    UIButton *loginOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [loginOutBtn setTitleColor:LTXDefaultsColor forState:UIControlStateNormal];
    [scrollview addSubview:loginOutBtn];
    loginOutBtn.backgroundColor = [UIColor whiteColor];
    [loginOutBtn addTarget:self action:@selector(clickLoginOutBtn:) forControlEvents:UIControlEventTouchUpInside];
    ViewRadius(loginOutBtn, 3);
    [loginOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(scrollview).offset(10);
        make.width.equalTo(@(ScreenW - 20));
        make.top.equalTo(myIncomeView.mas_bottom).offset(30);
        make.height.equalTo(@50);
    }];
    
    NSString *string = @"使用本软件即同意《注册协议》";
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:string];
    
    NSRange range = [string rangeOfString:@"《注册协议》"];
    
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attributedStr.length - range.location)];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:LTXDefaultsColor range:range];
    
    
    [attributedStr addAttribute:NSLinkAttributeName value:@"zhuce://" range:range];
    
    UITextView *prompt = [[UITextView alloc]init];
    prompt.linkTextAttributes = @{NSForegroundColorAttributeName: LTXDefaultsColor,
                                  NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                  NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
    //prompt.delegate = self;
    prompt.editable = NO;        //必须禁止输入，否则点击将弹出输入键盘
    prompt.scrollEnabled = NO;
    prompt.attributedText = attributedStr;
    prompt.font = [UIFont systemFontOfSize:12];
    prompt.userInteractionEnabled = YES;
    prompt.textAlignment = NSTextAlignmentCenter;
    prompt.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:prompt];
    
    CGFloat textWidht = [self widthForString:prompt andWidth:ScreenW];
    textWidht += 4;
    
//    [prompt mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(scrollview);
//        make.width.equalTo(@(textWidht));
//        make.top.equalTo(loginOutBtn.mas_bottom).offset(11);
//    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleRuleTap:)];
    [prompt addGestureRecognizer:tap];
}


- (float) widthForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.width;
}

- (void)meDescView:(YCLMeDescView *)meDescView clickCurrenPlateType:(MyClickType)type
{
    switch (type) {
        case MyClickType_Income:
            //收货地址
        {
            ReceiveGoodsVC *addressVC = [[ReceiveGoodsVC alloc] init];
            addressVC.type = ChooseAddress;
            
            addressVC.hidesBottomBarWhenPushed = YES;
            
            [self.navigationController pushViewController:addressVC animated:YES];
        }
            break;
        case MyClickType_Gathering_Code:
            //我的优惠
            break;
            
        default:
            break;
    }
}

/**
 点击了客服  打电话即可
 */
- (void)addUserClick
{
    HDSellerObject *obj = [HDSellerObject sellerMsg];
    
    openCall(obj.telPhone);
}


- (void)clickLoginOutBtn:(UIButton *)btn
{
    //退出登录
    [LTX_Common showAlertWithTitle:@"退出登录" msg:@"确认退出登录?" actions:@[@"是",@"否"] viewController:self callBack:^(NSString *title) {
        if ([title isEqualToString:@"是"]) {
            
            //清空account   清空数据库数据
        }
    }];
}

/**
 点击了消息中心按钮
 */
- (void)setting {
    showMessageAutoMiss(@"开发中,敬请期待!");
}


/**
 点击头像跳转个人信息
 */
- (void)personMessage
{
    //通过account 判断是否已经登录
    if (![HDAccount account]) {
        //没有登录执行登录方法
        [self logIn:nil];
    }
}


/**
 登录方法

 @param btn 登录按钮  没有登录的情况下  点击都是modle到登录界面
 */
- (void)logIn:(UIButton *)btn
{
    LTXNavgationViewController *loginNav = [[LTXNavgationViewController alloc]initWithRootViewController:[[YCLLoginViewController alloc]init]];
    
    [self presentViewController:loginNav animated:YES completion:nil];
}


/**
 点击账户余额 未登录跳转到去登录
 */
- (void)clickMoneyBtn
{
    if (![HDAccount account]) {
    
        [self logIn:nil];
    }
}


/**
 点击了积分
 */
- (void)clickCashBtn
{
    if (![HDAccount account]) {
        //跳转的和提现跳转的页面一样 TYPE不一样
        [self logIn:nil];
        return;
    }
}



- (void)setupDescData
{
    HDAccount *account = [HDAccount account];
    if (!account) return;
    //个人信息数据  请求到就更新
    //每次更新余额信息
//    [self.modelManager theBalanceOfWithUserID:account.userID token:account.token succe:^(NSString *message, YCLCashMoneyModel *model) {
//        self.moneyL.text = [NSString stringWithFormat:@"%@ 元",model.balanceIncludeFreeze];
//        self.cashL.text = [NSString stringWithFormat:@"%@ 元",model.prize];
//    } failure:^(NSString *message) {
//        TTDPRINT(@"%@",message);
//    }];

//    @weakify(self);
//    //因为字段返回的数量根据对用户信息的完善 随时可能不一样  所以  每次到这个页面  刷新一遍个人信息
//    [[[YCLPersonInfoModelManager alloc]init] getUserInfoWithUserID:account.userID token:account.token succe:^(NSString *message, YCLPersonInfoModel *model) {
//        @strongify(self);
//        if (model.errorCount > 0) {
//            NSString *str = [NSString stringWithFormat:@"%zd笔失败订单",model.errorCount];
//            NSRange range = [str rangeOfString:[NSString stringWithFormat:@"%zd",model.errorCount]];
//            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
//            [attributedStr addAttribute:NSForegroundColorAttributeName value:YCLDefaultColor range:range];
//            self.secondView.descLable2.attributedText = attributedStr;
//        }else
//        {
//            self.secondView.descLable2.text = @"暂无失败订单";
//        }
//
//        if (model.chaseCount > 0) {
//            NSString *str = [NSString stringWithFormat:@"%zd笔追号记录",model.chaseCount];
//            NSRange range = [str rangeOfString:[NSString stringWithFormat:@"%zd",model.chaseCount]];
//            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
//            [attributedStr addAttribute:NSForegroundColorAttributeName value:YCLDefaultColor range:range];
//            self.secondView.descLable2.attributedText = attributedStr;
//        }else
//        {
//            self.secondView.descLable2.text = @"暂无追号";
//        }
//
//        NSInteger redPackeetCount = [account.voucherDYCount integerValue];
//
//        if(redPackeetCount > 0) {
//            self.firstRowView.descLable2.text = [NSString stringWithFormat:@"%ld个红包", redPackeetCount];
//        }
//        else {
//            self.firstRowView.descLable2.text = @"暂无红包";
//        }
//
//    } failure:^(NSString *message) {
//        YCLMeDescView *firstView = (YCLMeDescView *)[self.view viewWithTag:FOLLOWNUMBER_TAG];
//        firstView.descLable2.text = @"暂无追号";
//    }];
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([[URL scheme] isEqualToString:@"zhuce"]) {
//        YCLHtmlViewController* viewController = [[YCLHtmlViewController alloc]init];
//        viewController.htmlTittle = @"注册协议";
//        viewController.urlStr = @"《注册协议》";
//        LTXNavgationViewController *htmlNav = [[LTXNavgationViewController alloc]initWithRootViewController:viewController];
//        [self presentViewController:htmlNav animated:YES completion:nil];
        return NO;
    }
    return YES;
}


- (void)handleRuleTap:(UITapGestureRecognizer *)recognizer
{
//    YCLHtmlViewController* viewController = [[YCLHtmlViewController alloc]init];
//    viewController.htmlTittle = @"注册协议";
//    viewController.urlStr = @"《注册协议》";
//    LTXNavgationViewController *htmlNav = [[LTXNavgationViewController alloc]initWithRootViewController:viewController];
//    [self presentViewController:htmlNav animated:YES completion:nil];
}



#pragma mark -  lazy

/**
 模型管理懒加载
 
 @return modelManager
 */
- (YCLMeModelManager *)modelManager
{
    if (!_modelManager) {
        _modelManager = [[YCLMeModelManager alloc]init];
    }
    
    return _modelManager;
}
@end
